#!/bin/bash
#
#Setting standards
#Don't change the values here. Create a file in either your global
#config path, or in /home/YourName/.config/. name it pacnotify.conf
#and fill in the values you want to override. Notice that Users
#jconfiguration files always have precedence, then the global one and at
#last the values set here.
sleeptime=1h	# time to wait between notifications
expires=120		# seconds to display the notification
lines=9			# lines of packages to display
icon=/usr/share/pixmaps/pacnotify32.png # which icon to use
backend=default  	# which backend to use one of: default pacman yaourt

#next few vars should not be touched
globalconf=/usr/share/pacnotify/pacnotify.conf
userconf=/home/$USER/.config/pacnotify.conf
tmpfile=/tmp/pacnotify.qqu
pid=$$
lockfile=/tmp/pacnotify.lock
#let's start checking for config

if [ -f $userconf ];
	then
		. $userconf
		initmsg=1
	elif [ -f $globalconf ];
		then
			. $globalconf
			initmsg=2
		else
			initmsg=3
fi

if [ -f $lockfile ];
	then
		initmsg=4
	else
		echo $pid > $lockfile
fi

time=$(($expires * 1000))
case $initmsg in
	1) notify-send Pacnotify "Starting up and setting defaults from userconf.\n<b>Backend: </b>$backend\n<b>Sleep: </b>$sleeptime min \n<b>Show: </b>$expires sec" -t $time -i $icon ;;
	2) notify-send Pacnotify "Starting up and setting defaults from globalconf.\n<b>Backend: </b>$backend\n<b>Sleep: </b>$sleeptime min \n<b>Show: </b>$expires sec" -t $time -i $icon ;;
	3) notify-send Pacnotify "Starting up and setting defaults.\n<b>Backend: </b>$backend\n</b>$sleeptime min \n<b>Show: </b>$expires sec" -t $time -i $icon ;;
	4) notify-send Pacnotify "Seems that pacnotify is already running. With PID: <b>`cat $lockfile`</b>. If not delete <b>$lockfile</b>.\n" -t $time -i $icon
	exit;;
esac
while [ true ]

	do
	case $backend in
	pacman)
		/usr/bin/pacman -Qqu > $tmpfile
	;;
	yaourt)
		/usr/bin/yaourt -Qqau > $tmpfile
		;;
	*|default|checkupdates)
		/usr/bin/checkupdates > $tmpfile
 ;;
	esac
		x_updates=`grep -c [a-z] $tmpfile`
		x_diff=$(($x_updates - $lines))
	if [ $x_diff -lt 1 ];
		then
			x_diff=0
		else
			more='\n<b>and '$x_diff' more</b>'
	fi
	pakete=`head -n $lines $tmpfile|cat -b`
	if [ $x_updates != 0 ];
		then
			notify-send Pacnotify "$p_runs_skip<b>$x_updates Updates</b>\n$pakete $more" -t $time -i $icon
	fi
	rm $tmpfile
	more=
	sleep $sleeptime
done
